package com.zqweb.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.zqweb.common.to.StockLockTo;
import com.zqweb.gulimall.ware.service.WareSkuService;
import com.zqweb.gulimall.ware.to.OrderTo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = {"stock.release.stock.queue"})
// 解锁库存的MQ监听器
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    // 自动解锁库存
    @RabbitHandler
    public void releaseLockedStock(StockLockTo stockLockTo, Message message, Channel channel) throws IOException {
        System.out.println("收到了解锁库存的消息...");
        try {
            wareSkuService.releaseLockStock(stockLockTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
    // 关单时主动触发解锁库存
    @RabbitHandler
    public void releaseLockedStock(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("收到了解锁库存的消息...");
        try {
            wareSkuService.releaseLockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }



}
